package com.wavefront.obj.parser.line;

import com.wavefront.obj.elements.Face;
import com.wavefront.obj.parser.LineParser;
import com.wavefront.obj.parser.ObjParser;

public class FaceParser extends LineParser {

	public FaceParser() {

	}

	@Override
	public void parse(String[] words) {
		super.parse(words);

		ObjParser.currentFace = ObjParser.currentMesh
				.createFace(Face.GL_TRIANGLES);

		switch (words.length) {
		case 4:
			parseTriangle();
			break;
		case 5:
			parseQuad();
			break;
		default:
			throw new RuntimeException("Could not identify face around");
		}

	}

	private void parseTriangle() {
		ObjParser.currentFace.setType(Face.GL_TRIANGLES);
		parseIndexedVertices(3);
	}

	private void parseQuad() {
		ObjParser.currentFace.setType(Face.GL_QUADS);
		parseIndexedVertices(4);
	}

	private void parseIndexedVertices(int vertexCount) {
		String[] vertexIndices = null;

		for (int i = 1; i <= vertexCount; i++) {

			int indexG = -1;
			int indexT = -1;
			int indexN = -1;

			vertexIndices = words[i].split("/");

			indexG = Integer.parseInt(vertexIndices[0]);

			if (vertexIndices.length == 2)
				indexT = Integer.parseInt(vertexIndices[1]);

			if (vertexIndices.length == 3) {
				if (!"".equals(vertexIndices[1]))
					indexT = Integer.parseInt(vertexIndices[1]);

				indexN = Integer.parseInt(vertexIndices[2]);
			}

			ObjParser.currentFace.createIndexedVertex(indexG, indexT, indexN);
		}
	}

	static int faceC = 0;
}
